package cn.com.twoke.game.server.handler;

import cn.com.twoke.game.common.entity.message.StartGameMessage;
import cn.com.twoke.game.common.handler.MessageHandler;
import cn.com.twoke.game.common.utils.MessageUtil;
import cn.com.twoke.game.server.cache.GameRoomCache;
import cn.com.twoke.game.server.cache.OnlineUserCache;
import cn.com.twoke.game.server.entity.GameRoom;

import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

public class StartGameMessageHandler implements MessageHandler<StartGameMessage> {

    @Override
    public void handle(Selector selector, SocketChannel channel, StartGameMessage message) throws IOException {
        MessageUtil.writeMessage(OnlineUserCache.CACHE.get(message.getRoomMasterId()), message);
        if (GameRoomCache.has(message.getRoomMasterId())) {
            GameRoomCache.get(message.getRoomMasterId()).getPlayerIds()
                   .forEach(item -> {
                       MessageUtil.writeMessage(
                               OnlineUserCache.CACHE.get(item),
                               message
                               );
                   });
           ;
        } else {
            GameRoomCache.add(message.getRoomMasterId(),
                    new GameRoom(message.getRoomId(), message.getRoomMasterId()));
        }
    }

}
